package com.zw.knowlege.aop;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.zw.common.response.ResponseResult;
import com.zw.knowlege.annotation.ParamCheckJson;
import com.zw.knowlege.common.ParamException;
import com.zw.knowlege.util.CommonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 参数统一校验
 */
@Aspect
@Component
public class ParamCheckAop {
    @Pointcut(value = "@annotation(com.zw.knowlege.annotation.ParamCheckJson)")
    public void paramCheckPointCut(){};



    @Around(value = "paramCheckPointCut() && @annotation(paramCheckJson)")
    public Object paramCheck(ProceedingJoinPoint joinPoint, ParamCheckJson paramCheckJson) throws Throwable{
        Object[] paramArgs = joinPoint.getArgs();
        if(JSONUtil.isJson(paramArgs[0].toString())){
            JSONObject paramJson = JSONObject.parseObject(paramArgs[0].toString());
            String[] expectArgs = paramCheckJson.args();
            String checkMessage = paramCheckValid(paramJson, expectArgs);
            if(!CommonUtils.nullOrEmpty(checkMessage)){
                return ResponseResult.failure(checkMessage);
            }
        }
        return joinPoint.proceed();
    }

    /**
     * 参数检查是否规范
     * @param paramJson
     * @param expectArgs
     * @return
     */
    private String paramCheckValid(JSONObject paramJson, String[] expectArgs){
        StringBuilder hasNoKey = new StringBuilder();
        StringBuilder hasNoValue = new StringBuilder();
        StringBuilder checkMessage = new StringBuilder();
        for(String fieldName : expectArgs){
            if(!paramJson.containsKey(fieldName)){
                hasNoKey.append(fieldName).append(",");
            }
            if(paramJson.containsKey(fieldName) && CommonUtils.nullOrEmpty(paramJson.getString(fieldName))){
                hasNoValue.append(fieldName).append(",");
            }

        }
        if(hasNoKey.length() > 0){
            checkMessage.append(String.format(ParamException.HAS_NO_KEY, hasNoKey.substring(0, hasNoKey.length() - 1)));
        }
        if(hasNoValue.length() > 0){
            checkMessage.append("且").append(String.format(ParamException.VALUE_IS_NULL, hasNoValue.substring(0, hasNoValue.length() - 1)));
        }
        return checkMessage.toString().startsWith("且") ? checkMessage.substring(1, checkMessage.length()) : checkMessage.toString();
    }
}
